//
//  ZYCircleActivity.m
//  CALayerAnimation
//
//  Created by linziyuan on 16/4/21.
//  Copyright © 2016年 creative. All rights reserved.
//

#import "ZYCircleActivity.h"

@interface ZYCircleActivity ()

@property (nonatomic, strong) CAShapeLayer *circleLayer;
@property (nonatomic, strong) CAGradientLayer *gradientLayer;
/** 进度条的起点 */
@property (nonatomic, assign) CGFloat startValue;
/** 进度条的终点 */
@property (nonatomic, assign) CGFloat endValue;
//
@property (nonatomic, assign) CGFloat currentEndValue;
/**线的路径*/
@property (nonatomic, strong) UIBezierPath *path;
//
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) CADisplayLink *linkTimer;
@end

@implementation ZYCircleActivity
{
    BOOL _isAnimating;
    BOOL _order;
    CGFloat _add;
}

+(Class)layerClass {
    return [CAGradientLayer class];
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        //创建shapeLayer
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        shapeLayer.fillColor = [UIColor clearColor].CGColor;
        shapeLayer.frame = self.bounds;
        CGFloat scale = [UIScreen mainScreen].scale;
        shapeLayer.lineWidth = 1.0 * scale;
        shapeLayer.lineWidth = 1.0;
        //[self.layer addSublayer:shapeLayer];
        shapeLayer.fillColor = [UIColor clearColor].CGColor;
        shapeLayer.strokeColor = [UIColor redColor].CGColor;
        self.circleLayer = shapeLayer;
        
//        //创建BezierPath
//        CGRect pathFrame = CGRectMake(shapeLayer.lineWidth + 0.5, shapeLayer.lineWidth  + 0.5, frame.size.width -  shapeLayer.lineWidth*2 - 1, frame.size.height -  shapeLayer.lineWidth*2 - 1);
//        // 创建贝塞尔曲线
//        UIBezierPath* path = [UIBezierPath bezierPathWithOvalInRect:pathFrame];
//        // 关联贝塞尔曲线
//        shapeLayer.path = path.CGPath;
        // 超出View本身的不要显示
        shapeLayer.masksToBounds = YES;
        
        CAGradientLayer* gradientLayer = (CAGradientLayer*)self.layer;
        [gradientLayer setStartPoint:CGPointMake(0, 0)];
        [gradientLayer setEndPoint:CGPointMake(1, 1)];
        self.gradientLayer = gradientLayer;
        
        NSMutableArray *rainBowColors = [NSMutableArray array];
        for (NSInteger hue = 0; hue <= 360; hue += 5) {
            UIColor *color = [UIColor colorWithHue:1.0*hue/360.0
                                        saturation:1.0
                                        brightness:1.0
                                             alpha:1.0];
            [rainBowColors addObject:(id)color.CGColor];
        }
        //self.gradientLayer.colors = [NSArray arrayWithArray:rainBowColors];
        self.colors = @[[UIColor redColor]];
        self.gradientLayer.mask = self.circleLayer;
        self.rate = 0.1;
        self.circleLayer.strokeStart = 0.0;
        self.circleLayer.strokeEnd = 0.0;
    }
    return self;
}

- (void)startAnimating {
    if (!_isAnimating) {
        self.hidden = NO;
        _isAnimating = YES;
        self.startValue = 0.0;
        self.endValue = 0.0;
        _add = 2;
        self.timer = [NSTimer scheduledTimerWithTimeInterval:self.rate
                                                      target:self
                                                    selector:@selector(circleAnimation)
                                                    userInfo:nil
                                                    repeats:YES];
        if (self.gradientLayer.colors.count > 2) {
            self.linkTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(gradientColor)];
            [self.linkTimer addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
        }
    }
}

- (void)stopAnimating {
    if (_isAnimating) {
        _isAnimating = NO;
        [self.timer invalidate];
        self.timer = nil;
        [self.linkTimer invalidate];
        self.linkTimer = nil;
        //self.startValue = self.currentEndValue;
        [self performSelector:@selector(hideSelf) withObject:self afterDelay:0.0];
    }
}

- (void)hideSelf {
    self.hidden = YES;
    [self.gradientLayer setStartPoint:CGPointMake(0, 0)];
    [self.gradientLayer setEndPoint:CGPointMake(1, 1)];
    self.startValue = 0.0;
    self.endValue = 0.0;
}

- (void)gradientColor {
    if (_order) {
        self.gradientLayer.startPoint = CGPointMake(self.gradientLayer.startPoint.x + 0.05, self.gradientLayer.startPoint.y + 0.05);
       // self.gradientLayer.endPoint = CGPointMake(self.gradientLayer.endPoint.x - 0.1, 1.0);
        if (self.gradientLayer.startPoint.y > 1) {
            _order = NO;
        }
    }else {
        self.gradientLayer.startPoint = CGPointMake( self.gradientLayer.startPoint.x - 0.05,  self.gradientLayer.startPoint.y - 0.05);
        //self.gradientLayer.endPoint = CGPointMake(self.gradientLayer.endPoint.x + 0.1, 1.0);
        if (self.gradientLayer.startPoint.y <= 0) {
            _order = YES;
        }
    }
}

- (void)circleAnimation {

    if (self.endValue > 1.0 && self.startValue <= 1.0) {
        self.startValue += sin(_add/M_PI*0.2);//_add;
    }else if(self.startValue== 0){
        //_add;
        if (self.endValue >= sin(_add/M_PI*0.2)*2) {
            self.endValue += sin(_add/M_PI*0.2);
        }else {
          self.endValue += sin(_add/M_PI*0.2)*2;
        }
    }
    if (self.endValue == 0) {
        self.startValue = 0;
    }
    if (self.startValue == self.endValue) {
        self.endValue = 0;
    }
    //self.endValue = 1.0;
    self.currentEndValue = self.endValue;
//    NSLog(@"startValue ---:  %.3f ~~~~~~~~~~endValue:~~ %.3f",self.startValue,self.endValue);
//    
//    self.endValue += sin(1/M_PI*0.02);
//    self.startValue += sin(1/M_PI*0.03);
//    self.endValue -= floor(self.endValue);
//    self.startValue -= floor(self.startValue);
}

#pragma mark  get && set
@synthesize startValue = _startValue;
-(void)setStartValue:(CGFloat)startValue{
    _startValue = startValue;
    _circleLayer.strokeStart = _startValue;
}
-(CGFloat)startValue{
    return _startValue;
}

@synthesize endValue = _endValue;
-(void)setEndValue:(CGFloat)endValue{
    _endValue = endValue;
    _circleLayer.strokeEnd = _endValue;
}
-(CGFloat)endValue{
    return _endValue;
}


@synthesize colors = _colors;
- (void)setColors:(NSArray<UIColor *> *)colors {
    NSMutableArray *rainBowColors = [NSMutableArray array];
    if (colors.count > 0) {
        NSMutableArray *fillArr = [NSMutableArray arrayWithArray:colors];
        if (colors.count < 2) {
            [fillArr addObject:colors[0]];
        }
        for (NSInteger i = 0; i < fillArr.count; i++) {
            if ([fillArr[i] isKindOfClass:[UIColor class]]) {
                UIColor *colorItem = fillArr[i];
                id layercolor = (__bridge id)colorItem.CGColor;
                [rainBowColors addObject:layercolor];
            }
        }
    }else {
        [rainBowColors addObject:(__bridge id)[UIColor redColor].CGColor];
        [rainBowColors addObject:(__bridge id)[UIColor redColor].CGColor];
    }
    self.gradientLayer.colors = [NSArray arrayWithArray:rainBowColors];
}

@synthesize rate = _rate;
- (void)setRate:(CGFloat)rate {
    _rate = rate;
    if (_rate <= 0.06) {
        _rate = 0.06;
    }
}
- (CGFloat)rate {
    return  _rate;
}

@synthesize progressLineWidth = _progressLineWidth;
-(void)setProgressLineWidth:(CGFloat)progresslineWidth{
    _progressLineWidth           = progresslineWidth;
    // 重新设置线宽，还要重新设置UIBezierPath所在的frame值
    CGFloat scale = [UIScreen mainScreen].scale;
    _circleLayer.lineWidth = _progressLineWidth * scale;
    _circleLayer.lineWidth = _progressLineWidth;
    // 贝塞尔曲线所在的frame值
    CGRect frame = _circleLayer.frame;
    CGRect pathFrame             = CGRectMake(_circleLayer.lineWidth, _circleLayer.lineWidth, frame.size.width - _circleLayer.lineWidth*2 - 1, frame.size.height - _circleLayer.lineWidth*2 - 1);
    // 创建贝塞尔曲线
    UIBezierPath* path           = [UIBezierPath bezierPathWithOvalInRect:pathFrame];
    // 关联贝塞尔曲线
    _circleLayer.path      = path.CGPath;
}
-(CGFloat)progressLineWidth{
    return _progressLineWidth;
}

@synthesize path = _path;
-(void)setPath:(UIBezierPath *)path{
    _path = path;
    _circleLayer.path = _path.CGPath;
}
-(UIBezierPath *)path{
    return _path;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    CGRect frame = self.frame;
    self.frame = frame;
}

- (void)setFrame:(CGRect)frame {
    [super setFrame:frame];
    self.path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(_circleLayer.lineWidth, _circleLayer.lineWidth, frame.size.width - _circleLayer.lineWidth*2 - 1, frame.size.height -  _circleLayer.lineWidth*2 - 1)];
}
- (CGRect)frame {
    return  [super frame];
}

@end
